<template>
  <div class="app-container">
    <el-form ref="form"
             :model="form"
             :rules="rules"
             :label-position="labelPosition"
             class="register-form">
      <el-row :gutter="40">
        <el-col :span="8">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="reportNo" label="报告文号">
                <el-input v-model="form.reportNo" type="text" auto-complete="off" placeholder="请输入报告文号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="customerName" label="客户名称（被审验单位名称）">
                <el-input v-model="form.customerName" type="text" auto-complete="off" placeholder="请输入客户名称（被审验单位名称）" />
              </el-form-item>
            </el-col>
         <!--   <el-col :span="12" v-judgeAccount="1">
              <el-form-item prop="firmName" label="事务所名称">
                <el-input v-model="form.firmName" type="text" auto-complete="off" placeholder="请输入事务所名称" />
              </el-form-item>
            </el-col>-->
            <el-col :span="12">
              <el-form-item prop="customerBusinessLicense" label="客户营业执照号">
                <el-input v-model="form.customerBusinessLicense" type="text" auto-complete="off" placeholder="请输入客户营业执照号" />
              </el-form-item>
            </el-col>
            <!--<el-col :span="12">
              <el-form-item prop="administrativeDivision" label="事务所行政区划">
                <el-input v-model="form.administrativeDivision" type="text" auto-complete="off" placeholder="请输入事务所行政区" />
              </el-form-item>
            </el-col>-->

           <!-- <el-col :span="12">
              <el-form-item prop="hasSecurities" label="是否具有证券资格">
                <el-select v-model="form.hasSecurities" placeholder="请选择">
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
            </el-col>-->
            <el-col :span="12">
              <el-form-item prop="isSecuritiesBusiness" label="是否属于证券业务">
                <el-select v-model="form.isSecuritiesBusiness" placeholder="请选择" @change="securitiesChange">
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="officeRemarks" :label="officeRemarksLable">
                <el-input v-model="form.officeRemarks" type="text" auto-complete="off" :placeholder="'请输入'+officeRemarksLable" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="firstBusinessTime" label="首次承接业务时间">
                <el-date-picker
                  v-model="form.firstBusinessTime"
                  type="date"
                  placeholder="请选择"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button
              :loading="loading1"
              size="medium"
              type="primary"
              @click.native.prevent="handleSubmit(1)"
            >
              <span v-if="!loading1">提 交</span>
              <span v-else>提 交 中...</span>
            </el-button>
            <el-button
              :loading="loading0"
              size="medium"
              type="primary"
              @click.native.prevent="handleSubmit(0)"
              v-hasPermi="['assurance:drafts']"
            >
              <span v-if="!loading0">保 存 草 稿</span>
              <span v-else>保 存 中...</span>
            </el-button>
            <el-button
              size="medium"
              type="default"
              @click.native.prevent="handleGoBack"
            >
              <span>返 回</span>
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item prop="reportType" label="报备类型">
                <el-select v-model="form.reportType"
                           placeholder="请选择"
                           clearable
                           filterable
                           @change="reportTypeChange"
                >
                  <el-option
                    v-for="(item,index) in reportTypeOption"
                    :key="index+'z'"
                    :label="item.dictLabel"
                    :value="item.dictValue" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="opinionType" label="意见类型(可填可选)">
                <el-select v-model="form.opinionType"
                           placeholder="请选择"
                           clearable
                           filterable

                           @clear="selectClear"
                           @change="selectChange"
                >
                  <el-option value=""/>
                  <el-option
                    v-for="(item,index) in opinionTypeOption"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictValue" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                prop="auditYear"
                label="审计年度"
                :required="form.reportType !== '验资业务' && form.reportType !== '专项审计业务' && form.reportType !== '其它'"
              >
                <!--<el-date-picker
                  v-model="form.auditYear"
                  type="year"
                  placeholder="请选择"
                  value-format="yyyy">
                </el-date-picker>-->
                <el-input v-model="form.auditYear" type="text" auto-complete="off" placeholder="请输入审计年度" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="reportTime" label="报告日期">
                <el-date-picker
                  v-model="form.reportTime"
                  type="date"
                  placeholder="请输入报告日期"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        <!--  <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item
                prop="reportCode"
                label="报备编码"
              >
                <el-input v-model="form.reportCode" type="text" auto-complete="off" placeholder="请输入报备编码"/>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item prop="filingTime" label="报备日期">
                <el-date-picker
                  v-model="form.filingTime"
                  type="date"
                  placeholder="请选择"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="reportStatus" label="报备状态">
                <el-select v-model="form.reportStatus" placeholder="请选择">
                  <el-option label="已报备" value="已报备" />
                  <el-option label="未报备" value="未报备" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>-->
          <el-row :gutter="20">
            <!--<el-col :span="6">
              <el-form-item prop="uploadTime" label="上传时间">
                <el-date-picker
                  v-model="form.uploadTime"
                  type="datetime"
                  placeholder="请选择"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>-->
            <el-col :span="6">
              <el-form-item prop="chargeAmount" label="收费金额（元）">
                <el-input-number v-model="form.chargeAmount" controls-position="right" :min="0" :precision="2" :max="9999999999" auto-complete="off" placeholder="请输入收费金额" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                prop="capitalVerificationAmount"
                label="验资金额（元）"
                :required="form.reportType === '验资业务'"
              >
                <el-input-number v-model="form.capitalVerificationAmount" controls-position="right" :min="0" :precision="2" :max="9999999999" auto-complete="off" placeholder="请输入验资金额" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="capitalVerificationCurrency"
                            label="验资币种"
                            :required="form.reportType === '验资业务'"
              >
                <el-select
                  v-model="form.capitalVerificationCurrency"
                  placeholder="请选择"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="(item,index) in currencyTypeOption"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictValue" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item prop="placeOfIncorporation"
                            label="公司注册地"
              >
                <el-select
                  v-model="form.placeOfIncorporation"
                  placeholder="请选择"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="(item,index) in addressPronOption"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictLabel" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="businessAddress"
                            label="业务所在地"
              >
                <el-select
                  v-model="form.businessAddress"
                  placeholder="请选择"
                  clearable
                                   cvvvlterable
                >
                  <el-option
                    v-for="(item,index) in addressPronOption"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictLabel" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-for="(item, index) in form.assuranceBusinessDataRegisterSignatures" :key="item.registerId">
            <el-col :span="6">
              <el-form-item
                :label="`签字注会${index+1}证书号`"
                :prop="'assuranceBusinessDataRegisterSignatures.' + index + '.registrationCertificateNo'"
                :rules="cpaRules"
              >
                <el-input v-model="item.registrationCertificateNo" type="text" auto-complete="off" placeholder="请输入签字注师证号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                :label="`签字注册会计师${index+1}`"
                :prop="'assuranceBusinessDataRegisterSignatures.' + index + '.registrantName'"
                :rules="cpaNameRules"
              >
                <el-input v-model="item.registrantName" type="text" auto-complete="off" placeholder="请输入签字注师姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item v-if="index===0 && form.assuranceBusinessDataRegisterSignatures.length < 4" label="增加会计师">
                <span class="btnPosition" @click.prevent="addData"><i class="el-icon-plus"></i></span>
              </el-form-item>
              <el-form-item v-if="index>1" label="删除会计师">
                <span class="btnPosition" @click.prevent="removeData(item)"><i class="el-icon-minus"></i></span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
  import { addAssurance,saveDraft,getAssurance,checkFirmName } from "@/api/system/assurance";
  import store from '@/store'
  export default {
    name: "AssuranceAdd",
    data() {
      let capitalAmount = (rule, value, callback) => {
        if (this.form.reportType === '验资业务' && !value) {
          return callback(new Error('请输入验资金额'));
        }
        callback();
      };
      let capitalCurrency = (rule, value, callback) => {
        if (this.form.reportType === '验资业务' && !value) {
          return callback(new Error('请选择验资币种'));
        }
        callback();
      };
      let yearValid = (rule, value, callback) => {
        // 报备类型为“验资业务”、“专项审计业务”、“其它”时，“审计年度”不必填。
        if (this.form.reportType !== '验资业务' && this.form.reportType !== '专项审计业务' && this.form.reportType !== '其它' && !value) {
          return callback(new Error('请输入审计年度'));
        }else{
          this.$refs.form.clearValidate(['auditYear']); // 清空单一校验
        }
        callback();
      };
     /* let cpa = (rule, value, callback) => {
        // 报备类型为“验资业务”、“专项审计业务”、“其它”时，“审计年度”不必填。
        if (this.form.reportType !== '其他' && !value) {
          return  callback();
        }else{
          this.$refs.form.clearValidate(['registrationCertificateNo1']); // 清空单一校验
          this.$refs.form.clearValidate(['registrantName1']); // 清空单一校验
          this.$refs.form.clearValidate(['registrationCertificateNo2']); // 清空单一校验
          this.$refs.form.clearValidate(['registrantName2']); // 清空单一校验
        }
        callback();
      };*/
      let validateFirmName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入事务所名称'));
        } else {
          checkFirmName(value).then(res=>{
            if(res.data && res.data>0){
              callback();
            }else{
              callback(new Error('事务所名称不存在'));
            }
          });
        }
      };
        let opinionTypeValid = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('意见类型不能为空'));
            } else {
                callback();
            }
        };
      return {
        MvalidateFirmName: validateFirmName,
        businessId: this.$route.query.businessId, // 传过来的 id
        labelPosition: "top",
        reportTypeOption: [], // 报备类型
        currencyTypeOption: [], // 验资币种
        opinionTypeOption: [], // 意见类型
        addressPronOption:[],//业务所在地，公司注册地 数据
        form: {
          assuranceBusinessDataRegisterSignatures:[
            {
              registrantName: '',
              registrationCertificateNo: ''
            },
            {
              registrantName: '',
              registrationCertificateNo: ''
            },
          ]
        },
        rules: {
          administrativeDivision: [{ required: true, trigger: "blur", message: "事务所行政区划不能为空" }], // 事务所行政区划 200
          hasSecurities: [{ required: true, trigger: "change", message: "是否具有证券资格不能为空" }], // 是否具有证券资格 5
          customerName: [{ required: true, trigger: "blur", message: "客户名称（被审验单位名称）不能为空" }], // 客户名称（被审验单位名称） 100
          customerBusinessLicense: [{ required: true, trigger: "blur", message: "客户营业执照号不能为空" }], // 客户营业执照号 100
          reportType: [{ required: true, trigger: "change", message: "报备类型不能为空" }], // 报备类型 50
          auditYear: [{ validator: yearValid, trigger: 'blur'}], // 审计年度 20
          reportNo: [{ required: true, trigger: "blur", message: "报告文号不能为空" }], // 报告文号 50
          //chargeAmount: [{ required: true, trigger: "blur", message: "收费金额不能为空" }], // 收费金额 20
         /* registrationCertificateNo1: [{validator: cpa, trigger: "blur", message: "签字注册师证号1不能为空" }], // 签字注册师证号1 50
          registrantName1: [{ validator: cpa, trigger: "blur", message: "签字注册师姓名2不能为空" }], // 签字注册师姓名1 20
          registrationCertificateNo2: [{ validator: cpa, trigger: "blur", message: "签字注册师证号2不能为空" }], // 签字注册师证号2 50
          registrantName2: [{ validator: cpa, trigger: "blur", message: "签字注册师姓名2不能为空" }], // 签字注册师姓名2 20*/
          isSecuritiesBusiness: [{ required: true, trigger: "change", message: "是否属于证券业务不能为空" }], // 是否属于证券业务 5
          opinionType: [{ required: true, validator:opinionTypeValid, trigger: "change", message: "意见类型不能为空" }], // 意见类型 10
          reportTime: [{ required: true, trigger: "blur", message: "报告日期不能为空" }],
          capitalVerificationAmount: [{validator: capitalAmount, trigger: 'blur'},], //验资金额
          capitalVerificationCurrency: [{validator: capitalCurrency, trigger: 'blur'},], //验资币种
          businessAddress: [{ required: true, trigger: "blur", message: "业务所在地不能为空" }],
          placeOfIncorporation: [{ required: true, trigger: "blur", message: "公司注册地不能为空" }],
          officeRemarks:[{ required: false, trigger: "blur", message: "请填写专项审计业务内容，如'竣工结算专项审计'"}]
        },
        loading0: false, // 草稿
        loading1: false, // 提交
        redirect: undefined,
        officeRemarksLable:"备注",
        cpaRules: {required: true, message: '签字注师证号不能为空', trigger: 'blur'},
        cpaNameRules: {required: true, message: '签字注师姓名不能为空', trigger: 'blur'},
      };
    },
    created() {
      const userInfo = store.getters.userInfo;
      if(userInfo){
        let isOfficeAccount = userInfo.isOfficeAccount;
        if(isOfficeAccount !== 1){
          this.rules.firmName= [
            { required: true, trigger: "blur", message: "事务所名称不能为空" },
            {validator: this.MvalidateFirmName, trigger: 'blur'}
          ];
        }
      }
      this.getDicts("report_type").then(response => {
        // 报备类型
        this.reportTypeOption = response.data;
      });
      this.getDicts("currency").then(response => {
        // 验资币种
        this.currencyTypeOption = response.data
      });
      this.getDicts("type_of_opinion").then(response => {
        // 意见类型
        this.opinionTypeOption = response.data
      });
      this.getDicts("business_address_pron").then(response => {
        this.addressPronOption = response.data
      });

      if(this.businessId){
        this.getDetail(this.businessId);
      }
    },
    deactivated () { //清除keep-alive的缓存
      this.$destroy(true)
    },
    methods: {
      selectBlur(e) {
        // 意见类型
        if (e.target.value !== '') {
          this.form.opinionType = e.target.value + '(其他)';
          this.$forceUpdate()
        }
      },
      selectClear() {
        this.form.opinionType = ''
        this.$forceUpdate()
      },
      reportTypeChange(val) {
          if(val==="验资业务" || val==="其它"){
              this.rules.opinionType =  [{ required: false, trigger: "change", message: "意见类型不能为空" }]
          }else{
              this.rules.opinionType =  [{ required: true, validator:(rule, value, callback) => {
                      if (value === '') {
                          callback(new Error('意见类型不能为空'));
                      } else {
                          callback();
                      }
                  }, trigger: "change", message: "意见类型不能为空" }]
          }
          if(val == "专项审计业务"){
              // this.rules.officeRemarks = [{ required: false, trigger: "blur", message: "请填写专项审计业务内容，如'竣工结算专项审计'，不超过10个字符"}]
              // this.officeRemarksLable = "备注"
            //暂时不需要
            this.rules.officeRemarks = [{ required: true, trigger: "blur", message: "请填写专项审计业务内容，如'竣工结算专项审计'"}]
              this.officeRemarksLable = "备注（请填写专项审计内容：如'竣工结算专项审计'）"
          }else{
            this.rules.officeRemarks = [{ required: false, trigger: "blur", message: "请填写专项审计业务内容，如'竣工结算专项审计'"}]
              this.officeRemarksLable = "备注"
          }
          if(val == "其它"){
            this.cpaRules = {required: false, message: '签字注师证号不能为空', trigger: 'blur'}
            this.cpaNameRules = {required: false, message: '签字注师姓名不能为空', trigger: 'blur'}
          }else{
            this.cpaRules = {required: true, message: '签字注师证号不能为空', trigger: 'blur'}
            this.cpaNameRules = {required: true, message: '签字注师姓名不能为空', trigger: 'blur'}
          }
          this.$forceUpdate()
      },
      securitiesChange(val){
        if(val  && val == "是"){
          this.rules.firstBusinessTime = { required: true, trigger: "blur", message: "首次承接业务时间不能为空"}
        }else{
          this.rules.firstBusinessTime = { required: false, trigger: "blur", message: "首次承接业务时间不能为空"}
        }
      },
      selectChange(val) {
        this.form.opinionType = val
        this.$forceUpdate()
      },
      getDetail(businessId){
        getAssurance(businessId).then(
          response => {
            if(response.msg && response.msg == "无权限"){
              this.$message({
                message: "无权限!",
                type: 'error'
              });
              this.$router.push("/assurance/list")
            }else {
              this.form = response.data;
              if( this.form.reportType == "其它"){
                this.cpaRules = {required: false, message: '签字注师证号不能为空', trigger: 'blur'}
                this.cpaNameRules = {required: false, message: '签字注师姓名不能为空', trigger: 'blur'}
              }else{
                this.cpaRules = {required: true, message: '签字注师证号不能为空', trigger: 'blur'}
                this.cpaNameRules = {required: true, message: '签字注师姓名不能为空', trigger: 'blur'}
              }
              if(this.form.reportType == "专项审计业务"){
                this.rules.officeRemarks = [{ required: true, trigger: "blur", message: "请填写专项审计业务内容，如'竣工结算专项审计'"}]
                this.officeRemarksLable = "备注（请填写专项审计内容：如'竣工结算专项审计'）"
              }else{
                this.rules.officeRemarks = [{ required: false, trigger: "blur", message: "请填写专项审计业务内容，如'竣工结算专项审计'"}]
                this.officeRemarksLable = "备注"
              }
              if(this.form.reportType=="验资业务"){
                this.rules.opinionType =  [{ required: false, trigger: "change", message: "意见类型不能为空" }]
              }else{
                this.rules.opinionType =  [{ required: true, validator:(rule, value, callback) => {
                    if (value === '') {
                      callback(new Error('意见类型不能为空'));
                    } else {
                      callback();
                    }
                  }, trigger: "change", message: "意见类型不能为空" }]
              }
            }
          }
        );
      },
      handleSubmit(status) {
        this.$refs.form.validate(valid => {
          if (valid) {
            let messageTitle;
            status === 0 ? this.loading0 = true : this.loading1 = true
            status === 0 ? messageTitle = '保存草稿' : messageTitle = '提交' // 0草稿，1保存，2删除
            this.form.status = status
            if(status===0){
              saveDraft(this.form).then(
                response => {
                  this.$confirm(`${messageTitle}成功`, '提示', {
                    confirmButtonText: '返回',
                    showClose: false,
                    showCancelButton: false,
                    type: 'success'
                  }).then(() => {
                    status === 0 ? this.loading0 = false : this.loading1 = false;
                    this.$router.go(-1);
                  });
                }
              ).catch(()=>{
                status === 0 ? this.loading0 = false : this.loading1 = false;
              });
            }else{
              addAssurance(this.form).then(
                response => {
                  this.$confirm(`${messageTitle}成功`, '提示', {
                    confirmButtonText: '返回',
                    showClose: false,
                    showCancelButton: false,
                    type: 'success'
                  }).then(() => {
                    status === 0 ? this.loading0 = false : this.loading1 = false;
                    this.$router.go(-1);
                  });
                }
              ).catch(()=>{
                status === 0 ? this.loading0 = false : this.loading1 = false;
              });
            }
          }
        });
      },
      handleGoBack() {
          this.$router.go(-1);
      },
      addData() {
        this.form.assuranceBusinessDataRegisterSignatures.push({
          registrantName: '',
          registrationCertificateNo: ''
        },);
      },
      removeData(item) {
        let index = this.form.assuranceBusinessDataRegisterSignatures.indexOf(item)
        if (index !== -1) {
          this.form.assuranceBusinessDataRegisterSignatures.splice(index, 1)
        }
      },
    }
  };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  ::v-deep .el-form-item__label{
    position: relative;
    font-size: 15px;
  }
  ::v-deep .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before {
    content: '';  // 去掉 * 号
  }
  ::v-deep .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:after {
    content: '*';  // 后置 * 号
    color: #ff4949;
    margin-right: 4px;
    right: -15px;
    top: 2px;
    position: absolute;
  }
  ::v-deep .el-input__inner{
    &::-webkit-input-placeholder {
      font-size: 13px;
    }
  }
  ::v-deep .el-date-editor.el-input, ::v-deep .el-select{
    width: 100%;
  }
  .btnPosition{
    display: inline-block;
    text-align: center;
    height: 36px;
    line-height: 36px;
    padding: 0 16px;
    cursor: pointer;
    border-radius: 4px;
    color: #848ae3;
    font-size: 18px;
    font-weight: 900;
    border: 1px solid rgba(132,138,227,.3);
    background: #fff;
    &:hover{
      border: 1px solid rgba(132,138,227,.9);
    }
  }
  .poBtn{
    margin-top: 50px;
    display: block;
    text-align: center
  }
</style>
